import React from "react";
import { Link } from 'react-router-dom'
import md5 from 'md5'
import { Form, Input, Button, Popover } from 'antd';
import { getForgetValidCode, getForgetEmailValidCode, saveNewPassword } from '../api';
import { t_alert } from "libs/utils";

const FormItem = Form.Item

const content = (
  <div>
    <p>Your Password Must</p>
    <p>･contain only alphanumeric characters</p>
    <p>･be between 6-30 characters</p>
    <p>･contain both letters and numbers </p>
  </div>
);

 class ForgetPassword extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      validCodeImg: '',
      emailValidCodeFlag: true,
      seconds: 'Get Code',
    }
  }

  componentDidMount() {
    this.getForgetValidCode()
  }

  getForgetValidCode = () => {
    getForgetValidCode(res => {
      this.setState({
        validCodeImg: res.data
      })
    })
  }

  getForgetEmailValidCode = () => {
    const form = this.props.form;
    const email = form.getFieldValue('email')
    let timer = null
    this.setState({
      seconds: 120,
      emailValidCodeFlag: true,
    }, () => {
      getForgetEmailValidCode({ email }, ()=>{
        timer = setInterval(() => {
          if(this.state.seconds===0){
            this.setState({
              seconds: 'Regain',
              emailValidCodeFlag: false
            })
            clearInterval(timer)
            timer = null
            return
          }
          this.setState((prevState)=>({seconds: prevState.seconds-1}))
        }, 1000)
      }, () => {
        setTimeout(() => {
          this.setState({
            seconds: 'Regain',
            emailValidCodeFlag: false
          })
        }, 1000);
      })
    })
  }

  validateEmail = (rule, value, callback) => {
    const seconds = this.state.seconds
    if(value && !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)){
      this.setState({
        emailValidCodeFlag: true
      })
      callback('Please enter the correct email')
    }else{
      this.setState({
        emailValidCodeFlag: typeof seconds === 'string' ? false : true
      })
      callback()
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const form = this.props.form
    form.validateFields((err, values) => {
      if (!err) {
        const { password:_password, email, validCode, emailCode } = values
        saveNewPassword({ password: md5(_password), email, validCode, emailCode }, () => {
          t_alert("Successful password modification, please login as soon as possible.");
          this.props.history.push('/teahcer/login')
          form.resetFields()
        }, this.getForgetValidCode)
      }
    });
  }

  render() {

    const { validCodeImg, seconds, emailValidCodeFlag } = this.state
    const { getFieldDecorator } = this.props.form
    // const

    return (
      <div className="teacher-forget">
        <div className="registry-header">
          <span className="title">Reset password</span>
        </div>
        <Form onSubmit={this.handleSubmit}
          onKeyDown={(e) => {
            if (e.keyCode == 13) {
              e.preventDefault();
            }
          }}
        >
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            {getFieldDecorator("email", {
              rules: [
                { required: true, message: "Email cannot be empty." },
                { validator: this.validateEmail }
              ]
            })(<p><Input placeholder="Email address" autoComplete="off" /></p>)}
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              {getFieldDecorator('validCode', {
                rules: [
                  { required: true, message: "Graphic Verification Code cannot be empty" },
                ],
              })(<p style={{ flex: 1 , marginRight: 20 }}><Input placeholder="Verification code" autoComplete="off" /></p>)}
              <div style={{ width: 100, height: 32 }} onClick={this.getForgetValidCode}>
                <img style={{ width: 100, height: 32, cursor: 'pointer', float: 'left' }} src={validCodeImg} alt="" />
              </div>
            </div>
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              {getFieldDecorator('emailCode', {
                rules: [
                  { required: true, message: "Email Verification code cannot be empty" },
                ],
              })(<Input style={{ flex: 1 }} placeholder="Email verification code" autoComplete="off" />)}
              <Button
                style={{ width: 100, marginLeft: 20 }}
                type="primary"
                disabled={emailValidCodeFlag}
                onClick={this.getForgetEmailValidCode}
              >{seconds}</Button>
            </div>
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            <Popover content={content} placement="left" trigger="click">
              {getFieldDecorator("password", {
                rules: [
                  { required: true, message: "Password cannot be empty" },
                  { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,30}$/, message: '6-30 bits combination of' +
                      ' letters and numbers' }
                ]
              })(<p><Input type="password" placeholder="Password" autoComplete="off" /></p>)}
            </Popover>
          </FormItem>
          <Button type="primary" className="registry-btn" htmlType="submit">Submit</Button>

          <Link to="/teacher/login_pad" className="registry-back" >Back</Link>
        </Form>
      </div>
    );
  }
}

export default Form.create()(ForgetPassword)